/**
 *
 */
package de.sendorian.app.forumArchive.download;

import java.io.IOException;
import java.util.List;

import javax.annotation.Nonnull;

import org.apache.log4j.Logger;

import de.sendorian.app.forumArchive.domain.Archive;
import de.sendorian.app.forumArchive.domain.Image;
import de.sendorian.app.forumArchive.domain.Topic;
import de.sendorian.app.forumArchive.repository.FileRepository;


public class ArchiveDownloadTask extends DownloadTaskBase implements DownloadTask, Runnable {
    private static final Logger logger = Logger.getLogger(ArchiveDownloadTask.class);

    private FileRepository fileRepository;


    ArchiveDownloadTask(@Nonnull Archive archive, @Nonnull final Topic topic, @Nonnull List<String> filesInArchives, FileRepository fileRepository) {
        super(archive, topic, filesInArchives);
        this.fileRepository = fileRepository;
    }


    /*
     * (non-Javadoc)
     * 
     * @see de.sendorian.app.forumArchive.download.DownloadTask#downloadFile()
     */
    public boolean downloadFile() {
        if (wasDownloadedBefore()) {
            logger.info("All images of archive "+file+" are already downloaded. Skipping.");
            return false;
        }

        Archive archive = (Archive) file;
        boolean downloaded = super.downloadFile();

        try {
            if (downloaded) {
                filesInArchives.addAll(archive.deflate());
                archive.delete();
            }
        } catch (IOException e) {
            logger.error("Could not deflate archive \"" + archive.getLocalPath() + "\"", e);
        }
        return downloaded;
    }


    /**
     * Returns true, if this archive was downloaded before and all images in
     * this archive can still be found in the download dir.
     * 
     */
    private boolean wasDownloadedBefore() {
        Archive alreadyDownloadedFile = (Archive) fileRepository.findByUrl(file.getUrl());
        // if the image list is empty this could be a new (but already saved) file or an error
        // in the database occured (perhaps an old version of the database) (Issue 75)
        if (alreadyDownloadedFile == null || alreadyDownloadedFile.getImages().isEmpty()) {
            return false;
        }

        boolean allImagesDownloaded = true;
        for (Image image : alreadyDownloadedFile.getImages()) {
            image.setLocalPath(file.getLocalPath());
            if (!image.existsLocally()) {
                // at least one image in this archive was not found
                allImagesDownloaded = false;
                break;
            }
        }
        return allImagesDownloaded;
    }
}
